package com.test.qpbgboot.show.service.impl;

import com.test.qpbgboot.backend.mapper.MerchantMapper;
import com.test.qpbgboot.base.enums.EnumController;
import com.test.qpbgboot.base.enums.GeneralStatusEnum;
import com.test.qpbgboot.base.exception.ServiceException;
import com.test.qpbgboot.base.response.ResultStatus;
import com.test.qpbgboot.base.utils.BaseUtils;
import com.test.qpbgboot.evaluation.mapper.OrderEvaluationMapper;
import com.test.qpbgboot.schedule.mapper.OrderMapper;
import com.test.qpbgboot.schedule.service.OrderService;
import com.test.qpbgboot.show.mapper.AreaMapper;
import com.test.qpbgboot.show.mapper.ShopMapper;
import com.test.qpbgboot.show.mapper.TagMapper;
import com.test.qpbgboot.show.pojo.dto.ShopQuery;
import com.test.qpbgboot.show.pojo.dto.ShopSaveParam;
import com.test.qpbgboot.show.pojo.dto.TagQuery;
import com.test.qpbgboot.show.pojo.entity.Shop;
import com.test.qpbgboot.show.pojo.vo.ShopVO;
import com.test.qpbgboot.show.pojo.vo.TagVO;
import com.test.qpbgboot.show.service.RoomService;
import com.test.qpbgboot.show.service.ShopService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
@Slf4j
@Transactional(rollbackFor = Exception.class)
public class ShopServiceImpl implements ShopService {

    @Value("${aliyun.oss.bucket-url}")
    private String bucketUrl;
    @Autowired
    private ShopMapper shopMapper;
    @Autowired
    private TagMapper tagMapper;
    @Autowired
    private OrderEvaluationMapper orderEvaluationMapper;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private AreaMapper areaMapper;
    @Autowired
    private MerchantMapper merchantMapper;
    @Autowired
    private OrderService orderService;
    @Autowired
    private RoomService roomService;

    @Override
    public List<ShopVO> shopSelect(ShopQuery shopQuery) {
        shopQuery.setTagIdList(stringToList(shopQuery.getTagIds()));
        log.debug("店家查询业务，参数:{}", shopQuery);
        if (shopQuery.getKeyword() != null) {
            TagQuery tagQuery = new TagQuery();
            tagQuery.setLabel(shopQuery.getKeyword());
            tagQuery.setFuzzySearchIs(true);
            List<TagVO> tagVOList = tagMapper.selectTagVOByTagQuery(tagQuery);
            shopQuery.setKeyTagIdList(tagVOList.stream().filter(Objects::nonNull)
                    .map(TagVO::getId).collect(Collectors.toList()));
        }
        List<ShopVO> shopVOList = shopMapper.selectShopVObyShopsQuery(shopQuery);
        if (shopVOList != null && !shopVOList.isEmpty()) {
            for (ShopVO shopVO : shopVOList) {
                additionalField(shopVO);
            }
        }
        log.debug("店家查询结果:{}", shopVOList);
        return shopVOList;
    }

    private List<Long> stringToList(String tagIds) {
        List<Long> tagIdList = new ArrayList<>();
        if (tagIds != null && !tagIds.isEmpty()) {
            List<String> tagIdStringList = Arrays.asList(tagIds.split(","));
            tagIdList = tagIdStringList.stream().filter(Objects::nonNull)
                    .map(Long::parseLong).collect(Collectors.toList());
        }
        return tagIdList;
    }

    @Override
    public void shopSave(ShopSaveParam shopSaveParam) {
        log.debug("店家保存业务，参数:{}", shopSaveParam);
        if (!EnumController.checkContain(shopSaveParam.getStatus(), "GeneralStatus")) {
            throw new ServiceException(ResultStatus.INCORRECT_STATUS);
        }
        Shop shop = new Shop();
        BeanUtils.copyProperties(shopSaveParam, shop);
        checkArea(shop);
        if (merchantMapper.selectEnableById(shopSaveParam.getMerchantId()) != 1) {
            throw new ServiceException(ResultStatus.INVALID_ID,"商家id无效");
        }

        List<Long> tagIdList = shopSaveParam.getTagIdList();
        if (tagIdList != null && !tagIdList.isEmpty()) {
            if (tagIdList.size() != tagMapper.selectCountByIdList(tagIdList)) {
                throw new ServiceException(ResultStatus.INVALID_ID, "标签id无效");
            }
            String tagIds = tagIdList.stream().filter(Objects::nonNull)
                    .map(String::valueOf).collect(Collectors.joining(","));
            shop.setTagIds(tagIds);
        }

        List<String> imgUrlList = shopSaveParam.getImgUrlList();
        String imgsUrl = BaseUtils.imgListToString(imgUrlList);
        imgsUrl = imgsUrl.replaceAll(bucketUrl, "bucketUrl");
        shop.setImgsUrl(imgsUrl);

        if (shop.getId() == null) {
            shopMapper.insert(shop);
        } else {
            shopMapper.update(shop);
        }
    }


    @Override
    public void shopLogOff(Long shopId) {
        log.debug("店家注销业务:{}", shopId);
        ShopQuery shopQuery = new ShopQuery();
        shopQuery.setId(shopId);
        List<ShopVO> shopVOList = shopMapper.selectShopVObyShopsQuery(shopQuery);
        if (shopVOList == null || shopVOList.isEmpty()) {
            throw new ServiceException(ResultStatus.INVALID_ID);
        }

        checkOrderStatusByShopId(shopId);
        orderService.orderAllCancelByShopId(shopId);
        roomService.roomInvisibledByShopId(shopId);

        Shop shop = new Shop();
        BeanUtils.copyProperties(shopVOList.get(0), shop);
        shop.setStatus(GeneralStatusEnum.DISABLE.getValue());
        shopMapper.update(shop);
    }


    private void additionalField(ShopVO shopVO) {
        BaseUtils.removeBlank(shopVO);
        String tagIds = shopVO.getTagIds();
        if (tagIds != null) {
            List<String> tagIdStringList = Arrays.asList(tagIds.split(","));
            List<Long> tagIdList = tagIdStringList.stream().filter(Objects::nonNull)
                    .map(Long::parseLong).collect(Collectors.toList());
            shopVO.setTagIdList(tagIdList);
        }
        String imgsUrl = shopVO.getImgsUrl();
        imgsUrl = imgsUrl.replaceAll("bucketUrl", bucketUrl);
        List<String> imgUrlList = BaseUtils.imgStringToList(imgsUrl);
        shopVO.setImgUrlList(imgUrlList);

        Double avgRating = orderEvaluationMapper
                .selectAvgRatingByShopId(shopVO.getId());
        shopVO.setAvgRating(avgRating != null ? avgRating : (double) 0);

        shopVO.setOrderNum(orderMapper
                .selectOrderNumInMonthByShopId(shopVO.getId()));

        Long likes = orderEvaluationMapper
                .selectLikesByShopId(shopVO.getId());
        shopVO.setLikes(likes != null ? likes : 0);
    }

    private void checkArea(Shop shop) {
        List<Integer> areaIdList = new ArrayList<>();
        Integer id = shop.getProvinceId();
        if (id != null) {
            areaIdList.add(id);
        }
        id = shop.getCityId();
        if (id != null && !areaIdList.contains(id)) {
            areaIdList.add(id);
        }
        id = shop.getDistrictId();
        if (id != null && !areaIdList.contains(id)) {
            areaIdList.add(id);
        }
        if (!areaIdList.isEmpty()) {
            if (areaIdList.size() != areaMapper.selectCountByIdList(areaIdList)) {
                throw new ServiceException(ResultStatus.INVALID_ID, "省市区id不存在");
            }
        }
    }

    /**
     * 检查是否有未完成的订单
     */
    private void checkOrderStatusByShopId(Long shopId) {
        if (orderMapper.selectUnfinishedCountByShopId(shopId) > 0) {
            throw new ServiceException(ResultStatus.INCORRECT_STATUS, "还有未完成的订单");
        }
    }

}
